package com.gsbelarus.gedemin.income;

import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.preference.PreferenceManager;

import com.gsbelarus.gedemin.income.sync.SyncReceiver;
import com.gsbelarus.gedemin.lib.sync.protocol.AlarmReceiver;
import com.gsbelarus.gedemin.lib.ui.GedeminApplication;

import java.util.Locale;

public class App extends GedeminApplication {

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        changeLocale();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        changeLocale();
    }

    @Override
    public AlarmReceiver getAlarmReceiver() {
        return new SyncReceiver();
    }

    private String getPrefLang() {
        SharedPreferences pref = PreferenceManager
                .getDefaultSharedPreferences(getBaseContext());
        String lang = pref.getString("list_language", "error");
        if (lang.equals("error"))
            return "ru";
        return lang;
    }

    public void changeLocale() {
        FontsUtil.setDefaultFont(getApplicationContext(), "MONOSPACE", "fonts/Roboto-Regular.ttf");

        Configuration config = getBaseContext().getResources().getConfiguration();
        String lang = getPrefLang();
        if (!config.locale.getLanguage().equals(lang)) {
            Locale locale = new Locale(lang);
            Locale.setDefault(locale);
            config.locale = locale;
            getBaseContext().getResources().updateConfiguration(config,
                    getBaseContext().getResources().getDisplayMetrics());
        }
    }
}
